<script setup lang="ts">
import { ref, onMounted,reactive, UnwrapRef } from 'vue'
import { teachCourseList, teachCourseCreate, teachCourseUpdate, teachCourseDeleted, coursecategoryList, courseCategoryCreate, courseCategoryUpdate, courseCategoryDeleted } from '../../stores/api/course'
import { useCounterStore } from '../../stores/counter'
import { useRoute, useRouter } from "vue-router";
import type { TableProps } from 'ant-design-vue';
import { ImgUrlPrefix } from '../../utils/config'
import type { Rule } from 'ant-design-vue/es/form';
import type { UploadProps } from 'ant-design-vue';
import { PictureOutlined, LoadingOutlined,QuestionCircleOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { upload, videoUpload } from '../../utils/upload' // 引入js
import WangEditor from '../../components/wangEditor.vue'
const store = useCounterStore()
const router:any = useRouter()
const info:any = ref({})
const loading = ref(false)
const imageUrl = ref<string>('');
const uploading = ref<boolean>(false);
const isShowAdd = ref(false)
const fileList = ref([]);
const fileList2 = ref<UploadProps['fileList']>([])
const videoUrl = ref<string>('')
const type = ref<string>('')
const id = ref('')
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
});
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '章名称',
    dataIndex: 'name',
    key: 'name'
  },
//   {
//     title: '权限',
//     dataIndex: 'permission',
//     key: 'permission',
//   },
//   {
//     title: '状态',
//     dataIndex: 'status',
//     key: 'status',
//   },
  {
    title: '更新时间',
    dataIndex: 'updated_at',
    key: 'updated_at',
  },
//   {
//     title: '锁定时间',
//     dataIndex: 'expire_time',
//     key: 'expire_time',
//   },
//   {
//     title: '直播流地址',
//     dataIndex: 'stream',
//     key: 'stream',
//   }
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
  },
];

const data_list:any = ref([])

interface FormState {
  title: string;
}
const formState: UnwrapRef<FormState> = reactive({
  title: '',
});

interface FormState2 {
  title: string;
  thumbnail: string;
  description: string;
  content: string;
  status: Number | undefined;
  sort: Number | string;
  p_id: Number;
}
const formRef = ref();
const labelCol = { span: 3 };
const wrapperCol = { span: 24 };
const formState2: UnwrapRef<FormState2> = reactive({
  title: '', // 名称
  thumbnail: '', // 封面图
  description: '', // 课程描述
  status: undefined, // 状态
  sort: '', //排序
  content: '', 
  p_id: 0 // 0 就是课程, 大于0 就是章节
});
const rules: Record<string, Rule[]> = {
  title: [
    { required: true, message: '请输入直播标题', trigger: 'change' },
  ],
  permission: [{ required: true, message: '请选择权限', trigger: 'change' }],
  status: [{ required: true, message: '请选择权限', trigger: 'change' }],
//   expire_time: [{ type: 'string' as const, required: true, message: '请选择时间' }]
};
// 
// 章节列表
const getCategoryList = () => {
    loading.value = true
    coursecategoryList({ page:  pagination.current, id: 0}, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            data_list.value = res.data.items
            loading.value = false
            pagination.total = res.data.total
        }
    }).catch((err: any) => {
        console.log(err)
        loading.value = false
    })
}

// 图片地址拼接
const getImgUrl = (val) => {
    const url = ImgUrlPrefix(val)
    return url
}

// 搜索
const onSubmit = () => {
    getCategoryList()
}
// 取消
const onCancel = () => {
    formState.title = ''
    getCategoryList()
}
// 新增
const getAdd = () => {
    isShowAdd.value = true
    type.value = 'add'
}
const handleTableChange = (pag) => {
  console.log(pag)
  pagination.current = pag
  getCategoryList()
};

// 图片上传--删除
const handleRemove: UploadProps['onRemove'] = file => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  imageUrl.value = ''
  formState2.thumbnail = ''
};
// 图片上传之前
const beforeUpload: UploadProps['beforeUpload'] = file => {
  fileList.value = [...(fileList.value || []), file];
  console.log(fileList.value)
  return true;
};
// 图片上传
const handleUpload = (data) => {
  uploading.value = true;
  console.log(fileList.value, data,'handleUpload')
  upload(data.file,res => {
      console.log(res,'ddddd')
      if(res) {
            const startIndex = res.indexOf('/') + 1;
            const urls = res.substring(startIndex);
            formState2.thumbnail = urls
            imageUrl.value = getImgUrl(urls)
            console.log(urls)
      }
      uploading.value = false;
  })
};

// 新增提交
const onSubmit2 = () => {
    formRef.value
    .validate()
    .then(() => {
      console.log('values', formState2);
      if(type.value == 'add') {
        addCourse()
      }else if(type.value == 'edit') {
        console.log('编辑')
        updateCourse()
      }
     })
     .catch(error => {
        console.log('error', error);
     });
}
// 取消
const resetForm = () => {
  formRef.value.resetFields();
  imageUrl.value = ''
  fileList.value = []
  isShowAdd.value = false
}

// 更新
const handleUpdate = (val:any) => {
    type.value = 'edit'
    isShowAdd.value = true
    id.value = val.id
    formState2.title = val.title // 标题
    formState2.thumbnail = val.thumbnail // 封面图
    formState2.description = val.description // 课程描述
    formState2.status = val.status// 状态
    formState2.sort = val.sort
    formState2.content = val.content
    imageUrl.value = getImgUrl(val.thumbnail)
}

const handlePeriod = (val) => {
    router.push({path: '/chapter', query: { id: val.id }})
}
// 调用新增接口
const addCourse = () => {
    let obj = {
        "description": formState2.description,
        "title": formState2.title,
        "thumbnail": formState2.thumbnail,
        "status": formState2.status,
        "sort": formState2.sort,
        "content": formState2.content,
        "p_id": formState2.p_id,
      }
      console.log(obj)
      courseCategoryCreate(obj, 'post').then((res: any) => {
            console.log(res)
            if(res.code == 200) {
                message.success('新建成功');
                formRef.value.resetFields();
                isShowAdd.value = false
                imageUrl.value = ''
                fileList.value = []
                getCategoryList()
            } else {
                message.error(res.message);
            }
      }).catch((err: any) => {
            console.log(err)
      })
}
// 调用编辑接口
const updateCourse = () => {
    let obj = {
        "id": id.value,
        "description": formState2.description,
        "title": formState2.title,
        "thumbnail": formState2.thumbnail,
        "p_id": formState2.p_id,
        "sort": formState2.sort,
        "content": formState2.content,
        "status": formState2.status,
    }
    console.log(obj)
    courseCategoryUpdate(obj, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            message.success('编辑成功');
            formRef.value.resetFields();
            isShowAdd.value = false
            imageUrl.value = ''
            fileList.value = []
            getCategoryList()
        } else {
            message.error(res.message);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 删除
const handleDelete = (id:any) => {
    console.log('删除')
    courseCategoryDeleted({
        "id": id
    }, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            message.success('删除成功');
            getCategoryList()
        } else {
            message.error(res.message);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}
onMounted(() => {
    getCategoryList()
})
</script>

<template>
    <div class="category">
        <div class="list-box">
            <div class="form-filter">
                <a-button type="primary" class="btn-sub" @click="getAdd">添加课程</a-button>
                <!-- <a-form layout="inline" :model="formState" >
                    <a-form-item label="名称">
                        <a-input v-model:value="formState.title" placeholder="请输入名称" />
                    </a-form-item>
                    <a-form-item>
                        <a-button type="primary" class="btn-ss" @click="onSubmit">搜索</a-button>
                        <a-button style="margin: 0 20px;" @click="onCancel">取 消</a-button>
                    </a-form-item>
                </a-form> -->
            </div>
            <div class="categoty-list">
                <a-card hoverable style="width: 260px;margin-right: 20px;margin-bottom: 20px;" v-for="item in data_list" :key="item.id" @click="handlePeriod(item)">
                    <template #cover>
                        <span>
                            <img :src="getImgUrl(item.thumbnail)" alt="" class="thumbnail_">
                        </span>
                    </template>
                    <template #actions>
                        <edit-outlined key="edit" @click.stop="handleUpdate(item)" />
                        <a-popconfirm title="是否确认删除吗？" ok-text="确定" cancel-text="取消" @confirm.stop="handleDelete(item.id)"> 
                            <template #icon><question-circle-outlined style="color: red" /></template>
                            <DeleteOutlined key="delete" />
                        </a-popconfirm>
                    </template>
                    <a-card-meta>
                        <template #title>
                            <div style="display: flex;justify-content: space-between;">
                                <div>{{ item.title }}</div>
                                <div>
                                    <a-tag color="green" v-if="item.status = 10">上架</a-tag>
                                    <a-tag color="cyan" v-else-if="item.status = 20">下架</a-tag>
                                </div>
                            </div>
                        </template>
                        <template #description>
                            <div>
                                <div class="category_content">{{ item.content ? item.content : '-' }}</div>
                                <div style="margin-top: 10px;">{{ store.timestampChangDate(item.created_at * 1000) }}</div>
                            </div>
                        </template>
                    </a-card-meta>
                </a-card>
            </div>
            <div style="text-align: right;">
                <a-pagination v-model:current="pagination.current" :total="pagination.total" show-less-items @change="handleTableChange" />
            </div>
            <!-- <a-table :columns="columns" :pagination="pagination"
                :loading="loading" :data-source="data_list" @change="handleTableChange">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'sort'">
                        <span>
                        {{ record.sort }}
                        </span>
                    </template>
                    <template v-if="column.key === 'name'">
                        <span>
                        {{ record.name ? record.name : '--' }}
                        </span>
                    </template>
                    <template v-else-if="column.key === 'status'">
                        <span>
                            <a-tag color="green" v-if="record.status == 10">上架</a-tag>
                            <a-tag color="cyan" v-else-if="record.status == 20">下架</a-tag>
                            <span v-else>--</span>
                        </span>
                    </template>
                    <template v-if="column.key === 'updated_at'">
                        <span>
                        {{ store.timestampChangDate(record.updated_at * 1000) || '--' }}
                        </span>
                    </template>
                    <template v-if="column.key === 'expire_time'">
                        <span>
                        {{ store.timestampChangDate(record.expire_time * 1000) || '--' }}
                        </span>
                    </template>
                    <template v-else-if="column.key === 'action'">
                        <span style="margin-right: 10px">
                          <a @click="handleUpdate(record)">编辑</a>
                        </span>
                        <span style="margin-right: 10px">
                            <a @click="handlePeriod(record)">查看节</a>
                        </span>
                        <span>
                            <a-popconfirm title="是否删除吗？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(record.id)"> 
                                <template #icon><question-circle-outlined style="color: red" /></template>
                                <a>删除</a>
                            </a-popconfirm>
                        </span>
                    </template>
                </template>
            </a-table> -->
        </div>
        <a-modal v-model:open="isShowAdd" :title="type == 'add' ? '新建课程' : type == 'edit' ? '编辑课程' : ''" width="700px" ok-text="" cancel-text="" @cancel="resetForm" :footer="null">
            <div class="live-left">
                <a-form
                    ref="formRef"
                    :model="formState2"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-item ref="title" label="课程名称" name="title">
                        <a-input v-model:value="formState2.title" class="input-item-dd" placeholder="请输入课程名称" />
                    </a-form-item>
                    <a-form-item label="状态" name="status">
                        <a-select v-model:value="formState2.status" placeholder="请选择状态">
                            <a-select-option :value="10">上架</a-select-option>
                            <a-select-option :value="20">下架</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item ref="sort" label="排序" name="sort">
                        <a-input v-model:value="formState2.sort" class="input-item-dd" placeholder="请输入排序" />
                    </a-form-item>
                    <a-form-item label="封面图" name="thumbnail">
                        <a-upload   class="cover-g" name="avatar" list-type="picture-card" :show-upload-list="false" :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove" :customRequest="handleUpload">
                            <!-- <img v-if="imageUrl" :src="imageUrl" alt="" /> -->
                            <div v-if="imageUrl" class="cover-image">
                                <img v-if="imageUrl" :src="imageUrl" alt="" />
                            </div>
                            <div v-else>
                                <loading-outlined v-if="uploading"></loading-outlined>
                                <PictureOutlined v-else :style="{fontSize: '22px'}" />
                                <div class="ant-upload-text">上传封面</div>
                            </div>
                        </a-upload>
                    </a-form-item>
                    <a-form-item label="课程内容" name="content">
                        <a-textarea
                            v-model:value="formState2.content"
                            placeholder="请输入课程内容"
                            :auto-size="{ minRows: 2}"
                            />
                    </a-form-item>
                    <a-form-item label="课程描述" name="description">
                        <a-textarea
                            v-model:value="formState2.description"
                            placeholder="请输入课程描述"
                            :auto-size="{ minRows: 2}"
                            show-count :maxlength="255" 
                            />
                        <!-- <WangEditor ref="WangEditorRef" v-model="formState2.description" /> -->
                    </a-form-item>
                    <a-form-item :wrapper-col="{ span: 24, offset: 4 }" style="text-align: right;">
                        <a-button class="btn-ss" type="primary" @click="onSubmit2">提交</a-button>
                        <a-button style="margin-left: 10px" @click="resetForm">取消</a-button>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<style scoped>
.category{
    padding: 15px;
}
.top-content-p{
    background-color: #fff;
    /* padding: 10px 15px;
    border-radius: 6px; */
}
.title-item-p{
    line-height: 40px;
    font-weight: bold;
    font-size: 16px;
}
.content-box{
    display: flex;
    flex-wrap: wrap;
    margin: 6px 0;
}
.name-item{
    line-height: 36px;
    min-width: 200px;
    color: #333;
    margin-right: 50px;
}
.name-item span{
    color: #000;
    margin-left:4px;
}
.content-ssv{
    color: #000;
    margin-left:4px;
}
.btn-ss{
    background-color: #fe5d26;
    height: 32px;
}
.btn-ss:hover{
    background-color: #fe5d26;
}
.btn-sub{
    background-color: #87d068;
    height: 32px;
}
.btn-sub:hover{
    background-color: #87d068;
}
.list-box{
    margin-top: 15px;
}

.form-filter{
   margin: 20px 0;   
   display: flex;
   justify-content: space-between;
}
.thumbnail_{
    width: 100%;
    height:200px;
    object-fit: cover;
}
.cover-g{
    /* background-color: rgb(51,52,63); */
    width: 130px;
    height: 132px;
    line-height: 26px;
    text-align: center;
    padding: 10px 0;
    border-radius: 10px;
}
.cover-image{
    width: 100%;
    height: 100%;
}
.cover-image img{
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.categoty-list{
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 17px;
}
.category_content{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>
